package com.example.screenappreceive

import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface

class H264Player(var surface: Surface) {


    var mediaCodec: MediaCodec
    val  width = 1080
    val  height = 1920
    init {
       mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
       val mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC,width,height)
       mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE,width*height)
       mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE,20)
       mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL,1)
       mediaCodec.configure(
               mediaFormat,
                surface,
                null,
                0
               )
       mediaCodec.start()
    }

    fun play(byteArray: ByteArray) {

      var  inBufferIndex =  mediaCodec.dequeueInputBuffer(100000)
        if (inBufferIndex >= 0) {
          var  inputBuffer =  mediaCodec.getInputBuffer(inBufferIndex)
          inputBuffer?.apply {
              clear()
              put(byteArray,0,byteArray.size)
              Log.v("david", "视频数据  " + byteArray.size);
              mediaCodec.queueInputBuffer(inBufferIndex,0,byteArray.size,System.currentTimeMillis(),0)
          }
        }
      var  bufferInfo =  MediaCodec.BufferInfo()
      var outBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo,100000)
        Log.v("outBufferIndex", "outBufferIndex  " + outBufferIndex);
       while (outBufferIndex >= 0) {
           Log.i("player", "解码器后长度  : " + bufferInfo.size);
           mediaCodec.releaseOutputBuffer(outBufferIndex,true)
           outBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo,0)
       }
    }

}